#include "tree.h"

CUStringList rule_list;

bool start( char *fn )
{
	CUTextFile file( fn, "r" );
	if( file.IsOpen() == false )	return false;

	int now_line=0;
	CUString prev_src="";
	while(1)	{
		CUString line;
		if( file.ReadLine( line ) == false ) break;
		now_line++;

		if( line.Find("###") == 0 )	continue;
		
		CUStringList ls;
		ls.TokenizeByChar( line, "\t", false );

		/*
		CUString reord = ls.GetAt( ls.GetSize()-2 );
		if( reord == "O" )	{
			rule_list.PushBack( line );
		}
		*/
		rule_list.PushBack( line );

	}

	return true;
}


bool filter( char *out_fn )
{
	CUTextFile out_file( out_fn, "w" );
	if( out_file.IsOpen() == false )	return false;

	map<string, bool> src_map;
	for( int i=0; i<rule_list.GetSize(); i++ )	{
		CUStringList ls;
		ls.TokenizeByChar( rule_list.GetAt(i), "\t", false );
		src_map[ ls.GetAt(0) ] = true;
	}


	int max_itr = 20;
	int cur=0;

	map<string, bool>::iterator itr = src_map.begin();
	while( itr != src_map.end() )	{

		CUString src = itr->first.c_str();
		double max_prob = -1;
		CUString max_str;


		for( int i=0; i<rule_list.GetSize(); i++ )	{
			CUStringList ls;
			ls.TokenizeByChar( rule_list.GetAt(i), "\t", false );

			if( src != ls.GetAt(0) )	{
				continue;
			}

			//fprintf( out_file.GetFP(), ">> %s\n", rule_list.GetAt(i) );
			double prob = atof( ls.GetAt( ls.GetSize() - 3 ) );
			if( prob > max_prob ) {
				max_prob = prob;
				max_str = rule_list.GetAt(i);
			}

		}
		int l = max_str.GetLength()-1;

		if( max_str.GetAt( l-2 ) == 'O' )	{
			if( max_str.GetAt( l ) == 'X' )	max_str.SetAt(l, 'O' );
			fprintf( out_file.GetFP(), "%s\n", max_str.GetStr() );
		}

		itr++;
		cur++;
		fprintf( stderr, "\r%d / %d", cur, src_map.size() );

	}
	fprintf( stderr,"\n" );


/*
	CUStringList ls;
	ls.TokenizeByChar( line, "\t", false );
	int s = ls.GetSize();
	CUString src = ls.GetAt(0);
	*/

	fprintf( stderr, "%d\n", rule_list.GetSize() );
	fprintf( stderr, "%d\n", src_map.size() );
}


int main( int argc, char *argv[] )
{
	if( argc != 3 )	{
		fprintf( stderr, "usage: bestrulefilter rule-file out-file\n" );
		return 1;
	}

	if( start( argv[1] ) == false )	{
		fprintf( stderr, "err\n" );
		return 1;
	}

	filter( argv[2] );

	return 0;
}


